import _ from 'lodash'
import MES from 'src/pages/factory/mine-message/components/mes.js'
const { msgIconList } = new MES()
export default {
  // 赋值给右侧
  SET_MSGDATA (state, activeMes) {
    if (_.isNil(activeMes)) {
      state.msgData = null
      state.msgSum = 0
      state.msgCount = 0
      state.scrollNum = 0
      return
    }
    let mesItem = state.mesListData.find(v => v.label === activeMes)
    state.scrollNum = _.cloneDeep(mesItem).num
    mesItem.num = 0
    let member = _.cloneDeep(state.mesListData)
    const params = member.find(v => v.label === activeMes)
    state.msgData = params
    state.msgSum = _.sum(member.map(v => v.num))
    state.msgCount = state.msgSum
  },
  // 订阅到的消息,
  SET_MSGBODY (state, params) {
    if (!Array.isArray(state.messageBodyData)) {
      state.messageBodyData = []
    }
    state.messageBodyData.push(params)
  },
  // 左侧显示的数据
  SET_MESLISTDATA (state, params) {
    state.mesListData = params
  },
  // 实时消息来的时候插入到原始数据上
  SET_MESCOUNT (state, { params, activeMes }) {
    const member = state.mesListData
    let mesItem = member.find(v => v.label === params.business)
    // 如果记录不存在,造成underfind 需要考虑进去
    // 左侧数据不存在,手动添加进去.需要进行枚举维护.
    if (_.isNil(mesItem)) {
      const cloneMesItem = msgIconList.get(params.business)
      mesItem = { labelName: cloneMesItem.name, label: cloneMesItem.id, num: 0, createTime: params.eventTime, ...cloneMesItem }
      state.mesListData.push(mesItem)
    }
    // 未读个数增加,以及时间更新
    mesItem.num++
    mesItem.createTime = params.eventTime
    if (activeMes === params.business) {
      const newMsg = {
        content: params.data,
        createTime: params.eventTime,
        id: params.id,
        business: params.business,
        businessName: params.subBusinessName,
        label: params.label,
        read: false
      }
      state.newMsg.push(newMsg)
      state.msgAllList.push(newMsg)
    }
    state.msgSum = _.sum(member.map(v => v.num))
    state.msgCount = state.msgSum
    state.mesListData = member.sort((a, b) => {
      return a.createTime < b.createTime ? 1 : -1
    })
  },

  // 清空数据
  CLEAR_MSG (state) {
    state.newMsg = []
  },

  // 清空未读消息个数显示
  CLEAR_SCROLLNUM (state) {
    state.scrollNum = 0
  },
  // 获取信息list
  // type 1 直接赋值 2 置顶到第一条未读新消息时 加入新来的消息 3向上滚动插入消息
  SET_MESLIST (state, { list, type }) {
    switch (type) {
      case 1:
        state.msgAllList = [...list]
        break
      case 3:
        state.msgAllList = [...list, ...state.newMsg]
        break
      default:
        state.msgAllList.unshift(...list)
    }
  },
  // type
  SET_NUM (state, { count, type }) {
    state.msgCount = type ? state.msgCount + count : count
  },
  // 右侧loading 加载
  SET_VISIBLE (state, visible) {
    state.isVisible = visible
  }
}
